import React, {Component} from 'react'
import {connect} from 'react-redux'
import actions from '../action'
import Toast from 'react-native-easy-toast'
import {
    createMaterialTopTabNavigator,
    createAppContainer,
} from 'react-navigation'
import {
    DeviceInfo,
    View,
    Text,
    StyleSheet,
    RefreshControl,
    ActivityIndicator,
    TouchableOpacity,
    FlatList,
    DeviceEventEmitter,
} from 'react-native'
import TrendingItem from '../common/TrendingItem'
import NavigationBar from '../common/NavigationBar'
import TrendingDialog, {timeSpans} from '../common/TrendingDialog'
import MaterialIcons from 'react-native-vector-icons/MaterialIcons'
import navigatorUtil from "../navigator/navigatorUtil";
import FavoriteDao from "../expand/dao/FavoriteDao";
import FavoriteUtil from "../util/FavoriteUtil";
import {FLAG_STORAGE} from "../expand/dao/DataStore";
import EventBus from 'react-native-event-bus'
import EventTypes from '../util/EventTypes'

const URL = 'https://github.com/trending/'
let queryStr = 'since=daily'
const THEME_COLOR = 'red'
const pageSize = 10
const EVENT_TYPE_TIME_SPAN_CHANGE = 'EVENT_TYPE_TIME_SPAN_CHANGE'
const flag = FLAG_STORAGE.flag_trending
const favoriteDao = new FavoriteDao(flag)


export default class TrendingPage extends Component {
    constructor(props) {
        super(props)
        this.tabNames = ['All', 'PHP', 'Java', 'IOS', 'Python', 'Javascript', 'Golang']
        this.state = {
            timeSpan: timeSpans[0]
        }
    }

    _genTabs() {
        let tabs = {}
        this.tabNames.forEach((item, index) => {
            tabs[`tab${index}`] = {
                screen: props => <TrendingTabPage {...props} tabLabel={item}/>,
                navigationOptions: {
                    title: item,
                    lazy: true,
                }
            }
        })
        return tabs
    }

    rendTitleView() {
        return <TouchableOpacity
            underlayColor='transparent'
            onPress={() => {
                this.dialog.show()
            }}
        >
            <View
                style={styles.titleView}
            >
                <Text>趋势 {this.state.timeSpan.showText}</Text>
                <MaterialIcons
                    name={'arrow-drop-down'}
                    size={36}
                    style={styles.arrow}
                />
            </View>
        </TouchableOpacity>
    }

    _tabNav() {
        if (!this.tabNav) {
            this.tabNav = createAppContainer(createMaterialTopTabNavigator(
                this._genTabs(),
                {
                    tabBarOptions: {
                        tabStyle: styles.tabStyle,
                        upperCaseLabel: false, //是否标签大写
                        scrollEnabled: true, //是否支持 选项卡滚动，默认False
                        style: {
                            backgroundColor: '#678',
                        },
                        indicatorStyle: styles.indicatorStyle,
                        labelStyle: styles.labelStyle,
                    }
                }
            ))
        }
        return this.tabNav
    }

    onSelectTimeSpan(tab) {
        this.dialog.dismiss()
        this.setState({
            timeSpan: timeSpans[tab]
        })
        DeviceEventEmitter.emit(EVENT_TYPE_TIME_SPAN_CHANGE, tab)
        queryStr = this.state.timeSpan.searchText
    }

    renderDialog() {
        return <TrendingDialog
            ref={dialog => this.dialog = dialog}
            onSelect={tab => this.onSelectTimeSpan.bind(this, tab)}
        />
    }

    render() {
        const TabNavigator = this._tabNav()
        let statusBar = {
            backgroundColor: '#678',
            barStyle: 'light-content',
            hidden: false,
        }
        const navigationBar = <NavigationBar
            // title={'趋势'}
            titleView={this.rendTitleView()}
            statusBar={statusBar}
            style={{backgroundColor: "#678"}}
        />
        return (
            <View style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0}}>
                {navigationBar}
                <TabNavigator/>
                {this.renderDialog()}
            </View>
        )

    }


}

class TrendingTab extends Component {
    constructor(props) {
        super(props);
        const {tabLabel} = this.props
        this.storeName = tabLabel
    }

    loadData(loadMore, isLoading = true) {

        const {onRefreshTrending, onLoadMoreTrending} = this.props
        const store = this._store();
        const url = this.genFetchUrl(this.storeName)
        if (loadMore) {
            onLoadMoreTrending(this.storeName, ++store.pageIndex, pageSize, store.items, favoriteDao, () => {
                this.refs.toast.show('没有更多了');
            })
        } else {
            onRefreshTrending(this.storeName, url, pageSize, favoriteDao, isLoading)
        }
    }

    _store() {
        const {trending} = this.props
        let store = trending[this.storeName];
        if (!store) {
            store = {
                items: [],
                isLoading: false,
                pageIndex: 1,
                projectModels: [], //需要显示的数据
                hideLoadingMore: true, //默认隐藏加载更多
            }
        }
        return store
    }

    genFetchUrl(storeName) {
        return URL + storeName + '?' + queryStr
    }

    renderItem(data) {
        const {item} = data
        return <TrendingItem
            projectModel={item}
            theme={this.props.theme}
            onSelect={(callback) => {
                navigatorUtil.goPage({
                    projectModel: item,
                    flag: FLAG_STORAGE.flag_trending,
                    callback

                }, 'DetailPage')
            }}
            onFavorite={(item, isFavorite) => FavoriteUtil.onFavorite(favoriteDao, item, isFavorite, FLAG_STORAGE.flag_trending)}
        />
    }

    _genIndicator() {
        return this._store().hideLoadingMore ? null :
            <View style={styles.indicatorContainer}>
                <ActivityIndicator style={styles.indicator}/>
                <Text>正在加载更多</Text>
            </View>
    }

    render() {
        let store = this._store()
        if (!store) {
            store = {
                items: [],
                isLoading: false,
            }
        }
        return <View>
            <FlatList
                data={store.projectModels}
                renderItem={item => this.renderItem(item)}
                keyExtractor={item => "" + item.item.fullName}
                refreshControl={
                    <RefreshControl
                        title={'Loading'}
                        titleColor={THEME_COLOR}
                        colors={[THEME_COLOR, 'yellow']}
                        refreshing={store.isLoading}
                        onRefresh={() => this.loadData(false)}
                    />
                }
                ListFooterComponent={
                    () => this._genIndicator()
                    // this._genIndicator.bind(this)
                }
                onEndReached={() => {
                    console.log('-----onEndReached------')
                    setTimeout(() => {  //为了确保执行 在 onMomentumScrollBegin之后
                        if (this.canLoadMore) {
                            this.loadData(true)
                            this.canLoadMore = false
                        }
                    }, 500)
                }}
                onMomentumScrollBegin={() => {  // 当滚动屏幕开始时触发
                    console.log('-----onMomentumScrollBegin------') //fix 修复onEndReached触发多次的问题
                    this.canLoadMore = true
                }}
                onEndReachedThreshold={0.1}
            />
            <Toast ref={'toast'} position={'center'}/>

        </View>
    }

    componentDidMount() {
        this.loadData()
        this.timeSpanChangeListener = DeviceEventEmitter.addListener(EVENT_TYPE_TIME_SPAN_CHANGE, tab => {
            queryStr = timeSpans[tab].searchText
            this.loadData()
        })
        EventBus.getInstance().addListener(EventTypes.BOTTOM_NAV_CHANGE, this.listener = data => {
            if (data.to === 1) {
                this.loadData(false, false)
            }
        })
    }

    componentWillUnmount() {
        if (this.timeSpanChangeListener) {
            this.timeSpanChangeListener.remove()
        }
        this.listener && EventBus.getInstance().removeListener(this.listener)
    }

}

const mapStateToProps = state => ({
    trending: state.trending,
})
const mapDispatchToProps = dispatch => ({
    onRefreshTrending: (storeName, url, pageSize, favoriteDao, isLoading) => dispatch(actions.onRefreshTrending(storeName, url, pageSize, favoriteDao, isLoading)),
    onLoadMoreTrending: (storeName, pageIndex, pageSize, items, favoriteDao, callBack) => dispatch(actions.onLoadMoreTrending(storeName, pageIndex, pageSize, items, favoriteDao, callBack))

})
// connect 只是一个function, 并不一定非要放在export后面
const TrendingTabPage = connect(mapStateToProps, mapDispatchToProps)(TrendingTab)

const styles = StyleSheet.create({
    welcome: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    tabStyle: {
        width: 100,
    },
    indicatorStyle: {
        height: 2,
        backgroundColor: 'white',
    },
    labelStyle: {
        fontSize: 13,
        marginTop: 6,
        marginBottom: 6,
    },
    indicatorContainer: {
        alignItems: 'center',
    },
    indicator: {
        color: 'red',
        margin: 10,
    },
    titleView: {
        flexDirection: 'row',

    },
    arrow: {
        marginTop: -8,
        marginLeft: -8,
    }
})
